package com.base.cn.platform.os.controller.course.cou.record;

import com.base.cn.platform.os.common.constants.CacheConstants;
import com.base.cn.platform.os.common.constants.CommonConstants;
import com.base.cn.platform.os.common.controller.BaseController;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.j2cache.J2CacheRegion;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.number.AmountUtils;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.action.ActionKey;
import com.base.cn.platform.os.common.utils.course.MaterialType;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.entity.course.cou.record.CourseLearnFlow;
import com.base.cn.platform.os.service.course.cou.record.CourseLearnFlowBiz;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.user.integral.CusUserIntegralService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 课程学习流水
 *
 * @author SK
 * @since 2018-06-13
 **/
@RestController
@RequestMapping("/course")
public class CourseLearnFlowController extends BaseController {

    @Autowired
    CourseLearnFlowBiz courseLearnFlowBiz;
    @Autowired
    SysConfigService  sysConfigService;
    @Autowired
    CusUserIntegralService cusUserIntegralService;
    @Autowired
    CustomCacheChannel commonCacheChannel;

    /**
     * 保存学习记录明细
     * @param courseLearnFlow
     * @return
     */
    @RequestMapping("/saveCourseLearnFlow")
    public Map<String,Object> saveCourseLearnFlow(@RequestBody  CourseLearnFlow courseLearnFlow,@RequestParam("finish") Integer finish){
        BigDecimal decimal = new BigDecimal(0);

        if(!DataUtil.idIsNotNull(courseLearnFlow.getBuyCourseId())||!DataUtil.idIsNotNull(courseLearnFlow.getCatalogId())||!DataUtil.idIsNotNull(courseLearnFlow.getCourseId())){
            return ResultUtil.ERROR("错误数据-----");
        }
        //判定学习时间是否有效
        long now = System.currentTimeMillis()+10000;
        //读取用户章节获取时间,设定留存一天
        Long lastTime = (Long)commonCacheChannel.get(J2CacheRegion.ONE_DAY_REGION.getKey(), CacheConstants.LAST_LEARNFLOW_TIME  + courseLearnFlow.getUserId()).getValue();
        Integer duration = courseLearnFlow.getDuration();
        long loadingTime = AmountUtils.safeMultiply(duration, 1000, 0).longValue();
        if(ObjectUtils.isEmpty(lastTime)){
            return ResultUtil.ERROR("学习记录保存失败");
        }
        if((lastTime + loadingTime) > now){
            loadingTime = now - lastTime;
            duration = AmountUtils.safeDivide(loadingTime,1000,0).intValue();
            courseLearnFlow.setDuration(duration);
        }
        if(courseLearnFlow.getDuration()>=30 ||(finish==2&&courseLearnFlow.getDuration()>0)) {
            if(courseLearnFlow.getMaterialTypeKey().equals(MaterialType.TYPE_KEY_ARTICLE.getKey())){
                if(courseLearnFlow.getDuration()>3600){
                    courseLearnFlow.setDuration(3600);
                }
            }
            courseLearnFlowBiz.saveFlowAndUpdateRecord(courseLearnFlow,finish);
            //添加观看积分
            cusUserIntegralService.addUserIntegral(ActionKey.COURSE,courseLearnFlow.getUserId(),courseLearnFlow.getMaterialId(),0,2);
        }
        return ResultUtil.SUCCESS("保存学习记录明细成功");
    }

    /**
     * 查询课程章节明细
     * @param courseLearnFlow
     * @param currentPage
     * @param pageSize
     * @return
     */
    @RequestMapping("/queryCoursePlayDetailPage")
    public PageInfo<CourseLearnFlow> queryCoursePlayDetailPage(@RequestBody  CourseLearnFlow courseLearnFlow,@RequestParam(value = "currentPage") int currentPage,
                                          @RequestParam(value = "pageSize",required = false,defaultValue = "10") int pageSize,@RequestParam(value = "setCourse") boolean setCourse,@RequestParam(value = "setCatalogData") boolean setCatalogData){
        Pagination page = new Pagination();
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        return   courseLearnFlowBiz.queryCoursePlayDetailPage(courseLearnFlow,page, setCourse, setCatalogData);
    }

    /**
     * 查询用户每日学习时间 用于折线图
     * @param courseLearnFlow
     * @return
     */
    @RequestMapping("/selectLearnTimeMap")
    public List<Map<String,Object>> selectLearnTimeMap(@RequestBody  CourseLearnFlow courseLearnFlow){
        return  courseLearnFlowBiz.selectLearnTimeMap(courseLearnFlow);
    }
    /**
     * 查询用户某天的日学习时间
     * @param courseLearnFlow
     * @return
     */
    @RequestMapping("/selectOneDayTime")
    public Integer selectOneDayTime(@RequestBody  CourseLearnFlow courseLearnFlow){
        return  courseLearnFlowBiz.selectOneDayTime(courseLearnFlow);
    }


    /**
     * 查询课程播放记录列表
     *
     * @param condition  课程播放记录查询条件
     * @param setCourse  设置课程
     * @param setCreator 设置前台用户
     * @return 课程播放记录列表
     */
    @RequestMapping("/findCoursePlayRecordFlowPage")
    public PageInfo<CourseLearnFlow> findCoursePlayRecordFlowPage(@RequestBody CourseLearnFlow condition,
                                                               @RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage,
                                                               @RequestParam(value = "pageSize",required = false,defaultValue = "10") int pageSize,
                                                               @RequestParam(value = "setCourse",required = false,defaultValue = "false") boolean setCourse,
                                                               @RequestParam(value = "setCreator",required = false,defaultValue = "false")boolean setCreator,
                                                               @RequestParam(value = "setCatalogData",required = false,defaultValue = "false") boolean setCatalogData,
                                                               @RequestParam(value = "setCatalogTeacher",required = false,defaultValue = "false") boolean setCatalogTeacher) {
        Pagination page = new Pagination();
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        return courseLearnFlowBiz.findCoursePlayRecordFlowPage(condition,page,setCourse,setCreator,setCatalogData,setCatalogTeacher);
    }



    /**
     * 根据素材id获取当天视频学习记录
     * @param materialId 视频素材id
     * @return
     */
    @RequestMapping("/findCourseLearnFlowByMaterialId")
    List<CourseLearnFlow> findCourseLearnFlowByMaterialId(@RequestParam("materialId") BigDecimal materialId){
        return courseLearnFlowBiz.find(" materialId= " + materialId + " AND TO_DAYS(createTime)=TO_DAYS(NOW()) ", null, null);
    }

    /**
     * 查询课程随堂练习记录
     *
     * @param condition  课程播放记录查询条件
     * @return 课程播放记录列表
     */
    @RequestMapping("/findCoursePlayRecordPracticeFlowPage")
    public Map findCoursePlayRecordPracticeFlowPage(@RequestBody CourseLearnFlow condition,
                                                                  @RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage,
                                                                  @RequestParam(value = "pageSize",required = false,defaultValue = "10") int pageSize) {
        Pagination page = new Pagination();
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        return courseLearnFlowBiz.findCoursePlayRecordPracticeFlowPage(condition,currentPage,pageSize);
    }


    /**
     * 查询用户的学习记录（用于生成折线图）
     *
     * @param condition  时间条件 {type 1 日 2 月 3 年 startTime 开始时间 endTime结束时间}
     * @return 课程播放记录列表
     */
    @RequestMapping("/selectLearningTrend")
    public List<Map> selectLearningTrend(@RequestBody  Map condition) {
        return courseLearnFlowBiz.selectLearningTrend(condition);

    }

}
